<template>
  <div class="form-design-fragment" style="position: relative;">
    <div>
      <vxe-toolbar>
        <template v-slot:buttons>
          <el-button type="primary" icon="el-icon-plus" size="small" @click="onEditPageForm">添加表单</el-button>
        </template>
      </vxe-toolbar>
      <el-table key="onlineForm" :data="formList" height="350" border header-cell-class-name="table-header-gray" size="small" :header-cell-style="{background:'#f4f4f4', color:'#717171' }">
        <el-table-column label="序号" header-align="center" align="center" type="index" width="55px" />
        <el-table-column label="表单标识" prop="formCode" width="180px" />
        <el-table-column label="表单名称" prop="formName" min-width="150px" />
        <el-table-column label="表单类型" prop="formType" width="100px">
          <template slot-scope="scope">
            <el-tag size="mini" effect="dark" :type="getFormTypeTag(scope.row.formType)">
              {{ SysOnlineFormType.getValue(scope.row.formType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180px">
          <template slot-scope="scope">
            <el-button size="mini" type="text" @click="onDesignPageForm(scope.row)">页面设计</el-button>
            <el-button class="table-btn success" size="mini" type="text" @click="onEditPageForm(scope.row)">编辑</el-button>
            <el-button class="table-btn delete" size="mini" type="text" style="color: #F56C6C;" @click="onDeletePageForm(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 在线表单子表单设计
    <FormGenerator
      v-if="currentForm != null"
      style="width: 100%;"
      :page-type="formPageData.pageType"
      :height="clientHeight - 80"
      :form="currentForm"
      :table-list="getTableInfo"
      :datasource-table-list="getPageDatasourceTableList"
      :form-list="formList"
      :form-datasource-list="pageDatasourceList"
      @tableCreate="onQueryCreateClick"
      @close="onCloseFormDesign"
    /> -->
  </div>
</template>

<script>
import '@/components/Dialog'
import '@/staticDict/onlineStaticDict.js'
import { findItemFromList } from '@/utils'
/* eslint-disable-next-line */
import rules from '@/utils/validate.js'
/* eslint-disable-next-line */
import { uploadMixin, statsDateRangeMixin } from '@/core/mixins'
import EditOnlineForm from './editOnlineForm.vue'
import FormGenerator from '../components/formGenerator.vue'
import {
  OnlinePageController,
  OnlineDblinkController,
  OnlineDatasourceRelationController,
  OnlineDictController,
  OnlineFormController,
  OnlineColumnController,
  OnlineVirtualColumnController
} from '@/api/onlineController.js'

export default {
  name: 'OnlineFormDesignList',
  // components: {
  //   FormGenerator
  // },
  mixins: [uploadMixin, statsDateRangeMixin],
  props: {
    pageId: {
      type: String,
      default: undefined
    }
  },
  data() {
    return {
      dirty: false,
      // 页面基础信息
      formPageData: {
        pageId: undefined,
        pageCode: undefined,
        pageName: undefined,
        published: false,
        pageType: this.SysOnlinePageType.BIZ,
        status: this.SysOnlinePageStatus.BASIC
      },
      // 页面数据模型列表
      pageDatasourceList: [],
      // 数据库信息
      dblinkInfo: {},
      // 当前选中表单
      currentForm: undefined,
      dictList: [],
      // 子表单列表
      formList: [],
      clientHeight: this.$store.getters.clientHeight,
      currentTable: undefined,
      virtualColumnTable: undefined
    }
  },
  computed: {
    isEdit() {
      return this.formPageData.pageId != null && this.formPageData.pageId !== ''
    },
    getPageDatasource() {
      return this.pageDatasourceList[0]
    },
    getPageDatasourceTableList() {
      if (this.getPageDatasource == null) return []

      const tableList = []
      // 添加主表信息
      tableList.push({
        id: this.getPageDatasource.datasourceId,
        tableName: this.getPageDatasource.masterTableIdDictMap.name,
        tableId: this.getPageDatasource.masterTableId,
        relationType: undefined,
        masterColumnName: undefined,
        slaveColumnName: undefined,
        cascadeDelete: false,
        leftJoin: false,
        tag: this.getPageDatasource
      })
      // 添加关联从表信息
      if (Array.isArray(this.getPageDatasource.relationList)) {
        this.getPageDatasource.relationList.forEach(relation => {
          tableList.push({
            id: relation.relationId,
            tableName: relation.slaveTable.tableName,
            tableId: relation.slaveTableId,
            relationType: relation.relationType,
            masterColumnName: (relation.masterColumn || {}).columnName || '未知字段',
            slaveColumnName: (relation.slaveColumn || {}).columnName || '未知字段',
            cascadeDelete: relation.cascadeDelete,
            leftJoin: relation.leftJoin,
            tag: relation
          })
        })
      }
      return tableList
    },
    getTableInfo() {
      return this.currentForm.tableList
    }
  },
  watch: {
  },
  mounted() {
    this.loadOnlineDictList().catch(e => {})
    this.loadDblinkList().then(res => {
      return this.initPageInfo()
    }).then(res => {
      this.formPageData = {
        pageId: res.data.pageId,
        pageCode: res.data.pageCode,
        pageName: res.data.pageName,
        published: res.data.published,
        pageType: res.data.pageType,
        status: res.data.status
      }
      this.initPageDatasourceInfo(this.formPageData.pageId)
      this.initPageFormList(this.formPageData.pageId)
    }).catch(e => {})
  },
  methods: {
    onCancel(isSuccess) {
      if (this.observer != null) {
        this.observer.cancel(isSuccess)
      }
    },
    onQueryCreateClick() {

    },
    getFormTypeTag(formType) {
      switch (formType) {
        case this.SysOnlineFormType.QUERY: return 'success'
        case this.SysOnlineFormType.FORM: return 'primary'
        case this.SysOnlinePageType.FLOW: return 'warning'
        default: return 'info'
      }
    },
    onCloseFormDesign() {
      this.currentForm = null
      this.initPageFormList(this.formPageData.pageId).catch(e => {})
    },
    loadOnlineDictList() {
      return new Promise((resolve, reject) => {
        OnlineDictController.list({}).then(res => {
          this.dictList = res.data.dataList
          resolve()
        }).catch(e => {
          reject(e)
        })
      })
    },
    /**
     * 获取数据库信息
     */
    loadDblinkList() {
      return new Promise((resolve, reject) => {
        this.dblinkInfo = {}
        OnlineDblinkController.list({}).then(res => {
          res.data.dataList.forEach(item => {
            this.dblinkInfo[item.dblinkId] = {
              ...item,
              tableList: undefined
            }
          })
          resolve()
        }).catch(e => {
          reject(e)
        })
      })
    },
    /**
     * 获取数据模型关联信息
     */
    loadDatasourceRelation() {
      if (this.getPageDatasource == null) return Promise.resolve()

      return OnlineDatasourceRelationController.list({
        onlineDatasourceRelationDtoFilter: {
          datasourceId: this.getPageDatasource.datasourceId
        }
      })
    },
    /**
     * 初始化页面基础信息
     */
    initPageInfo() {
      this.formPageData = {
        pageId: undefined,
        pageCode: undefined,
        pageName: undefined,
        pageType: this.SysOnlinePageType.BIZ,
        status: this.SysOnlinePageStatus.BASIC
      }
      this.activeStep = this.SysOnlinePageSettingStep.BASIC

      if (this.pageId != null || this.formPageData.pageId != null) {
        const params = {
          pageId: this.pageId || this.formPageData.pageId
        }

        return OnlinePageController.view(params)
      } else {
        return Promise.resolve()
      }
    },
    /**
     * 初始化页面数据模型信息
     */
    initPageDatasourceInfo(pageId) {
      return new Promise((resolve, reject) => {
        OnlinePageController.listOnlinePageDatasource({
          pageId: pageId
        }).then(res => {
          this.pageDatasourceList = res.data.dataList
          return this.loadDatasourceRelation()
        }).then(res => {
          this.pageDatasourceList = this.pageDatasourceList.map(item => {
            if (item.datasourceId === this.getPageDatasource.datasourceId) {
              item.relationList = res.data.dataList || []
            }
            return item
          })
          resolve()
        }).catch(e => {
          reject(e)
        })
      })
    },
    /**
     * 获取页面子表单列表
     */
    initPageFormList(pageId) {
      return new Promise((resolve, reject) => {
        OnlineFormController.list({
          onlineFormDtoFilter: {
            pageId: pageId
          },
          orderParam: [
            {
              fieldName: 'createTime',
              asc: true
            }
          ]
        }).then(res => {
          this.formList = res.data.dataList
          this.formList.forEach(item => {
            item.formData = JSON.parse(item.widgetJson)
          })
          resolve()
        }).catch(e => {
          reject(e)
        })
      })
    },
    loadOnlineTableColumns(tableId) {
      if (tableId == null || tableId === '') return Promise.reject()

      return new Promise((resolve, reject) => {
        const params = {
          onlineColumnDtoFilter: {
            tableId
          }
        }

        OnlineColumnController.list(params).then(res => {
          resolve(res.data.dataList)
        }).catch(e => {
          reject(e)
        })
      })
    },
    loadOnlineVirtualColumnList() {
      return new Promise((resolve, reject) => {
        const params = {
          onlineVirtualColumnDtoFilter: {
            datasourceId: this.getPageDatasource.datasourceId
          }
        }

        OnlineVirtualColumnController.list(params).then(res => {
          res.data.dataList.forEach(item => {
            item.columnId = item.virtualColumnId
            item.columnName = item.objectFieldName
            item.columnComment = item.columnPrompt
            item.isVirtualColumn = true
          })
          resolve(res.data.dataList)
        }).catch(e => {
          reject(e)
        })
      })
    },
    onDesignPageForm(row) {
      const masterTable = findItemFromList(this.getPageDatasourceTableList, row.masterTableId, 'tableId')
      if (masterTable) {
        if (masterTable && masterTable.relationType == null) {
          // 主表获取虚拟字段列
          this.loadOnlineVirtualColumnList().then(res => {
            const virtualColumnList = res
            // 数据源主表的查询以及编辑页面
            let httpCalls = []
            // 返回主表和一对一从表，编辑页面同时返回一对多从表
            const templateList = this.getPageDatasourceTableList.filter(item => {
              return (
                item.relationType == null ||
                item.relationType === this.SysOnlineRelationType.ONE_TO_ONE ||
                (row.formType !== this.SysOnlineFormType.QUERY && item.relationType === this.SysOnlineRelationType.ONE_TO_MANY)
              )
            })
            httpCalls = templateList.map(item => {
              return this.loadOnlineTableColumns(item.tableId)
            })
            Promise.all(httpCalls).then(res => {
              const tableList = res.map((item, index) => {
                templateList[index].columnList = item
                // 数据源主表，添加虚拟字段
                if (templateList[index].tableId === row.masterTableId) {
                  templateList[index].columnList.push(...virtualColumnList)
                }
                return templateList[index]
              })
              row.tableList = tableList
              this.currentForm = row
              const params = {
                pageType: this.formPageData.pageType,
                height: 400,
                form: this.currentForm,
                tableList: this.getTableInfo,
                datasourceTableList: this.getPageDatasourceTableList,
                formList: this.formList,
                formDatasourceList: this.pageDatasourceList
              }

              this.$dialog.show('页面设计', FormGenerator, {
                area: ['1200px', '680px'], offset: 'auto'
              }, params).catch(e => {})
            }).catch(e => {
              console.log(e)
            })
          }).catch(e => {
            console.log(e)
          })
        } else {
          this.loadOnlineTableColumns(masterTable.tableId).then(res => {
            masterTable.columnList = res
            row.tableList = [masterTable]
            this.currentForm = row
            const params = {
              pageType: this.formPageData.pageType,
              height: 400,
              form: this.currentForm,
              tableList: this.getTableInfo,
              datasourceTableList: this.getPageDatasourceTableList,
              formList: this.formList,
              formDatasourceList: this.pageDatasourceList
            }

            this.$dialog.show('页面设计', FormGenerator, {
              area: ['1200px', '680px'], offset: 'auto'
            }, params).catch(e => {})
          }).catch(e => {
            console.log(e)
          })
        }
      }
    },
    /**
     * 编辑子表单
     */
    onEditPageForm(row) {
      this.$dialog.show('编辑表单', EditOnlineForm, {
        area: '600px'
      }, {
        pageId: this.formPageData.pageId,
        pageType: this.formPageData.pageType,
        datasourceId: this.getPageDatasource.datasourceId,
        datasourceTableList: this.getPageDatasourceTableList,
        form: row
      }).then(res => {
        this.initPageFormList(this.formPageData.pageId)
      }).catch(e => {})
    },
    onDeletePageForm(row) {
      this.$confirm('是否删除此表单？').then(res => {
        const params = {
          formId: row.formId
        }

        return OnlineFormController.delete(params)
      }).then(res => {
        this.$message.success('删除成功！')
        this.initPageFormList(this.formPageData.pageId)
      }).catch(e => {})
    }
  }
}
</script>

<style  lang="scss">
  .form-design-fragment {
    display: flex;

    flex-direction: column;
    margin: 10px 10px 20px 10px;
    .blueLink {
      color: #409eff;
      font-size: 14px;
      margin-left: 20px;
      cursor: pointer;
    }
    .btnList {
      margin-top:20px;
      display: flex;
      justify-content: right;
      float: right;
      .submitBtn {
        margin-right: 30px;
      }
    }
    .fromFlex {
      height: 36px;
      display: flex;
      align-items: center;
    }
    .base-info {
      display: flex;
      margin-bottom: 20px;
      .basics-info {
        width: 100%;
      }
    }
  }
</style>
